import json
import logging
import requests
from utils.connect_redis import connect_redis


def ApiAut(appkey,username):
    """
    获取token

    """
    url = "https://www.scnlkf.com/rest/fastlogin/v1.0?app_key={}&username={}&type=2".format(appkey,username)
    headers = {
        "Content-Type":"application/x-www-form-urlencoded; charset=UTF-8",
        "Authorization":"1qaz@WSX"
    }
    res = requests.post(url=url,headers=headers,verify=False)
    a=res.content.decode()
    access_token=json.loads(a)["access_token"]
    r=connect_redis(db=6)
    r.set(username, access_token, ex=172800)
    return access_token,a

def PhoneBindInter(telA,telX,telB,appkey,bind_url,recordFlag,userData):
    """
    点击呼叫
    """
    username = 'CaaSSY093'
    logger = logging.getLogger('log')
    try:
        headers = {
            "Content-Type":"application/json;charset=UTF-8"
        }
        r=connect_redis(db=6)
        access_token=r.get(username)
        if access_token:
            pass
        else:
            access_token=ApiAut(appkey,username)[0]
        url = bind_url+"?app_key={}&access_token={}".format(appkey,access_token)
        Xnumber = str(int(telX))
        Anumber = str(int(telA))
        Bnumber = str(int(telB))
        # 主叫号码
        callerNum ='+86'+Anumber
        # 关系小号
        relationNum = '+86'+Xnumber
        # 被叫号码
        calleeNum = '+86'+Bnumber
        # 提示音
        recordHintTone = 'mute.wav'
        import base64
        a = 'http://39.102.37.193:2034/callstatus_v1/'.encode()  # 将‘str’转为二进制
        b = base64.b64encode(a)  # 将a转为base64编码
        b=b.decode()
        c = 'http://39.102.37.193:2034/feeInfo_v1/'.encode()  # 将‘str’转为二进制
        d = base64.b64encode(c)  # 将a转为base64编码
        d = d.decode()
        data = {
                    "callerNbr":callerNum,
                    "calleeNbr":calleeNum,
                    "bindNbr":relationNum,
                    "recordFlag": recordFlag,
                    "recordHintTone": recordHintTone,
                    "statusUrl":b,
                    "feeUrl":d,
                    "userData":userData
                }
        data = json.dumps(data)
        print('data',data)
        result = requests.post(url=url,data=data,headers=headers,verify=False,timeout=5)
        print('result',result)
        e=result.content.decode()
        res = json.loads(e)
        print('res',res)
        if res["resultcode"] == '0':
            pass
        elif res['resultcode'] in ["1020001", "1010002"]:
            res['resultcode'] = '100001'
        elif res['resultcode'] in ["1023002"]:
            logger.error('四川移动应用响应超时{}--A:{}--X:{}--B:{}'.format(res['resultcode'],telA,telX,telB))
            res['resultcode'] = '100002'
        elif res['resultcode'] in ["1010010", "1020154", "1020165", "1010009"]:
            logger.error('四川移动应用并发错误{}--A:{}--X:{}--B:{}'.format(res['resultcode'], telA, telX, telB))
            res['resultcode'] = '100003'
        elif res['resultcode'] in ["1010001", "1020002"]:
            logger.error('四川移动应用内部错误{}--A:{}--X:{}--B:{}'.format(res['resultcode'], telA, telX, telB))
            res['resultcode'] = '100004'
        elif res['resultcode'] in ["1010004", "1010005"]:
            try:
                access_token1=ApiAut(appkey, username=username)[0]
            except Exception as e:
                logger.error('呼叫调用四川移动tokenget错误{}'.format(e))
                return res,relationNum
            url1 = bind_url + "?app_key={}&access_token={}".format(appkey, access_token1)
            result = requests.post(url=url1, data=data, headers=headers, verify=False, timeout=5)
            f = result.content.decode()
            res = json.loads(f)
            if res["resultcode"] == '0':
                pass
            elif res['resultcode'] in ["1020001", "1010002"]:
                res['resultcode'] = '100001'
            elif res['resultcode'] in ["1023002"]:
                logger.error('四川移动应用响应超时{}--A:{}--X:{}--B:{}'.format(res['resultcode'], telA, telX, telB))
                res['resultcode'] = '100002'
            elif res['resultcode'] in ["1010010", "1020154", "1020165", "1010009"]:
                logger.error('四川移动应用并发错误{}--A:{}--X:{}--B:{}'.format(res['resultcode'], telA, telX, telB))
                res['resultcode'] = '100003'
            elif res['resultcode'] in ["1010001", "1020002"]:
                logger.error('四川移动应用内部错误{}--A:{}--X:{}--B:{}'.format(res['resultcode'], telA, telX, telB))
                res['resultcode'] = '100004'
            else:
                logger.error('四川移动应用其他错误{}--A:{}--X:{}--B:{}'.format(res['resultcode'], telA, telX, telB))
        else:
            logger.error('四川移动应用其他错误{}--A:{}--X:{}--B:{}'.format(res['resultcode'], telA, telX, telB))
        return res,relationNum
    except Exception as e:
        print(e)
        logger.error('四川移动双呼点击呼叫调用失败A:{},B:{},ERROR:{}'.format(telA,telB,str(e)))
        return
def PhoneUnbindInter(appkey,unbind_url,sessionid):
    """
    解绑

    """
    r = connect_redis(db=6)
    try:
        access_token = r.get(username)
        # print(access_token)
    except:
        access_token = ApiAut(appkey, username)[0]
    headers = {
        "Content-Type": "application/json;charset=UTF-8"
    }
    url = unbind_url + "?app_key={}&access_token={}".format( appkey,access_token)
    data = {
        "sessionid": sessionid,
        "signal": "call_stop",

    }
    data = json.dumps(data)
    res = requests.post(url, headers=headers,data=data, verify=False, timeout=2)
    # print(res)
    # print(res.content.decode())

def apirefreshtoken(refresh_token):
    """
    刷新token

    """
    headers = {
        "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8"
    }
    url = "https://www.scnlkf.com/omp/oauth/refresh"
    data = {
        "app_key": appkey,
        "app_secret": secret,
        "refresh_token":refresh_token,

    }
    data = json.dumps(data)
    res = requests.post(url, headers=headers, data=data, verify=False, timeout=2)

def getrecord(appkey,recordDomain,access_token,fileName,sessionId):
    headers = {
        "Content-Type": "application/json;charset=UTF-8",
    }
    url = record_url + "?app_key={}&access_token={}&recordDomain={}&fileName={}".format(appkey, access_token,recordDomain,fileName)
    # print(url)
    res = requests.get(url, headers=headers, verify=False,allow_redirects=False,timeout=2)
    # print(res)
    # str_url =res.content.decode()
    # print(str_url)
    a=res.headers
    # b=res.status_code
    # c=res.text
    # d=res.history
    # print(a)
    apiUrl=a['Location']
    r = requests.get(apiUrl, verify=False, allow_redirects=False, timeout=2, stream=True)
    with open('./audio/{}.wav'.format(sessionId),'wb') as f:
        f.write(r.content)
#{'Location': 'https://223.87.15.163/sp-r6ynd5bt11sza7g0dliim5d1qjx9/20080308494612039413542.wav?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Date=20200803T093320Z&X-Amz-SignedHeaders=host&X-Amz-Expires=604800&X-Amz-Credential=BC580C195A416CD72304%2F20200803%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Signature=f3f75f3ed0f7c315c8711ba05e77c18d3401e3e1ef10bb19d3859ce7944a0f2e', 'Date': 'Mon, 03 Aug 2020 09:33:20 GMT', 'Server': 'OMPBaseS', 'Content-Type': 'text/plain;charset=ISO-8859-1', 'Content-Length': '0', 'Connection': 'close'}




if __name__ == '__main__':
    appkey = '961I14zEcgM50UKSeQb2v0TlI6y0'  #线上appley
    username = 'CaaSSY093'                 #线上username
    telA = '15612918360'
    telB = '18910826810'
    # telX = '02860749950' #线上x
    telX = '02860749959' #线上x
    secret='1qaz@WSX'
    bind_url = 'https://www.scnlkf.com/rest/httpsessions/click2Call/v2.0'
    unbind_url = "https://www.scnlkf.com/rest/httpsessions/callStop/v2.0"
    record_url="https://www.scnlkf.com/rest/provision/voice/record/v1.0"

    # ApiAut(appkey,username)
    result=PhoneBindInter(telA, telX, telB, appkey, bind_url,recordFlag='true')
    # print(result)
    # PhoneUnbindInter(appkey, unbind_url, sessionid)
    # getrecord(appkey=appkey,access_token=access_token,recordDomain='ostorusr.signal.system',fileName='20090102020812052919139.wav',sessionId=sessionid)